#!/bin/bash

#this file change the sparse matrix format from:
#1 2 0.3
#1 3 0.2
#2 1 0.2
#2 2 0.1
#
# to 
#1
#2 0.3
#3 0.2
#2
#1 0.2
#2 0.1
#this format is used by SVDLIBC(mit)

if [ $# -lt 1 ]
then
    print "Usage: changeMatrixFormat srcFile "
else
    srcFile=$1
fi

awk 'BEGIN{
    print "298866 21029 4744675";
}
{
    if (1 == NR) {
        str=($2-1)" "$3;
        currentRow = $1-1;
        num = 1;
    }
    else if(($1-1) == currentRow) {
        str=str"\n"($2-1)" "$3;
        ++num;
    }
    else {
        print num;
        print str;
        emptyLines = $1-1-currentRow-1;
        for (i=0; i< emptyLines; ++i) {
            print "1";
            print "1 0";
        }
        str = ($2-1)" "$3;
        num = 1;
        currentRow = $1-1;
    }
}
END {
    print num;
    print str;
}' $srcFile
